package com.my.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.entity.AttendanceLog;
import com.my.service.AttendanceLogService;
import com.my.service.CurriculumService;
import com.my.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("api")
@CrossOrigin
public class CurriculumApiController {

    @Autowired
    private CurriculumService service;
    @Autowired
    private AttendanceLogService aalService;

    @GetMapping("currentClockIn")
    public Rest currentClockIn(Long userId) {
        Map<String, Object> map = service.getCurrentClockInCurriculum(userId);
        if(map == null) {
            return Rest.ok("无需打卡");
        }
        AttendanceLog log = aalService.getByUserAttendCreate(Convert.toLong(map.get("userId")), Convert.toLong(map.get("curriculumId")), DateUtil.format(new Date(), "yyyy-MM-dd"));
        if(log == null) {
            aalService.save(new AttendanceLog().setUserId(Convert.toLong(map.get("userId"))).setCurriculumId(Convert.toLong(map.get("curriculumId"))).setStatus(Convert.toInt(map.get("status"), 0) == 0 ? 1 : 3));
            return Rest.ok("打卡成功！");
        }
        return Rest.ok("已打卡！");
    }

    @GetMapping("upToDate")
    public Rest upToDate(Long userId) {
        return Rest.ok().setData("date", service.upToDate(userId)).setData("absenteeismCount", aalService.count(new QueryWrapper<AttendanceLog>().eq("user_id", userId).eq("status", 2)));
    }

}
